onload = bodyload

var tm;
var act_num=0;

var myXhr;

function setVar(elem,prop,val)
{
	if(document.getElementById(elem))
			eval('document.getElementById(elem).'+prop+"='"+val+"'");
}


function show_action(num){
	if(num==act_num) {return hideMenu();}
	cancelClose(act_num);
	hideMenu();
	act_num=num;
	setVar('actbutton'+num,'className','actbutton');
	setVar('cm'+num,'style.display','block');
	cancelClose(num);
	}

function cancelClose(num){
	if(num!=act_num) return;
    if(tm) {
        clearTimeout(tm);
  	  }
	}

function closeMenu(num) {
	if(num!=act_num) return;
    tm = setTimeout("hideMenu()",300);
	}	

function hideMenu() {
	if(act_num!=0)	{
		setVar('actbutton'+act_num,'className','');
		setVar('cm'+act_num,'style.display','none');
		act_num=0;
		}
	}
	
function cancelContext(){
    if(tm) {
        clearTimeout(tm);
	  }
	}

function closeContext() {
	tm = setTimeout("hideContext()",100);
	}	

function hideContext() {
		if(document.getElementById('context'))document.getElementById('context').style.display='none';
	}

function bodyload()
{	
	tds = document.getElementsByTagName('td');
    for (var i = 0; i < tds.length; i++) 	{
		if(tds[i].className=='clickable') {
			tds[i].onmouseover=function() { this.style.backgroundPosition='0% 100%' };
			tds[i].onmouseout=function() { this.style.backgroundPosition='0% 500%' };
			}
		}	
	tds = document.getElementsByTagName('button');
    for (var i = 0; i < tds.length; i++) 	{
			tds[i].onmouseover=function() { this.style.backgroundPosition='0px -26px' };
			tds[i].onmouseout=function() { this.style.backgroundPosition='0px 0px' };
		}		
	
	Init();
	makeResizeable();

	formForAdd = document.getElementById("formdiv").innerHTML
}


function sorta(col)
{
	if(!document.getElementById("tabs_filter") || !document.getElementById("tabs_filter").value)
	{
		if( (col=='pos' && sortdir=='desc') || (col=='pos' && col!=sortby) ) {newlink=sortbase;dir='asc';}
		else{
			if(col!=sortby) dir='asc';
			else dir=(sortdir=='desc'?'asc':'desc');
			newlink = sortbase+'sortby='+col+'&sortdir='+dir;
		}
	}
	else
	{
		filter=document.getElementById("tabs_filter").value
		if( (col=='pos' && sortdir=='desc') || (col=='pos' && col!=sortby) ) {newlink=sortbase+"filter="+filter;dir='asc';}
		else{
			if(col!=sortby) dir='asc';
			else dir=(sortdir=='desc'?'asc':'desc');
			newlink = sortbase+'sortby='+col+'&sortdir='+dir+"&filter="+filter;
		}
	}
	
	sortby=col;
	sortdir=dir;
	
	return alist(newlink)
}

function alist(href)
{
	xmlHttp=GetXmlHttpObject()

	if(document.getElementById("navigator"))document.getElementById("navigator").style.borderBottom='0';
	document.getElementById("listloader").style.display='block';
	
	if(href.indexOf('?')<0) href+='?'
	var url=href+"&ajaxpart=list"
	url+="&rand="+Math.floor(Math.random()*100000);
	xmlHttp.onreadystatechange=listLoaded 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	
	return false
}

function aform(href)
{
	xmlHttp=GetXmlHttpObject()

	document.getElementById("formfields").style.display = 'none'
	document.getElementById("formloader").style.display = ''
	document.getElementById("formdiv").style.display = 'block'
	document.getElementById("listdiv").style.display = 'none'
	
	if(href.indexOf('?')<0) href+='?'
	var url=href+"&ajaxpart=form"
	url+="&rand="+Math.floor(Math.random()*100000);
	xmlHttp.onreadystatechange=formLoaded 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	
	return false
}


function listLoaded() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById("listdiv").innerHTML = xmlHttp.responseText
		
		tds = document.getElementsByTagName('td');
	    for (var i = 0; i < tds.length; i++) 	{
		if(tds[i].className=='clickable') {
			tds[i].onmouseover=function() { this.style.backgroundPosition='0% 100%' };
			tds[i].onmouseout=function() { this.style.backgroundPosition='0% 500%' };
			}
		}
		sortbase = document.getElementById('sortbase_hidden').value;
		makeResizeable();
	} 
} 

function formLoaded() { 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 		
		document.getElementById("formdiv").innerHTML = xmlHttp.responseText
		
		tds = document.getElementsByTagName('button');
	    for (var i = 0; i < tds.length; i++) 	{
			tds[i].onmouseover=function() { this.style.backgroundPosition='0px -26px' };
			tds[i].onmouseout=function() { this.style.backgroundPosition='0px 0px' };
		}		
		
		eval($('jshidden').value);
		makeResizeable();
	} 
} 


function massDelete(href)
{
	delcount=0

	href+='id='
	tds = document.getElementsByTagName('input');
    for (var i = 0; i < tds.length; i++) 	{
		if( tds[i].id.substring(0,3)=="del" && tds[i].checked){
			delcount++
			href += tds[i].id.substring(3,tds[i].id.length) + ","
		}		
	}		
	if(delcount==0) return false;
	if(confirm("Вы действительно хотите удалить "+delcount+" элемент"+ending(delcount)+"?"))
	{
		href=href.substring(0,href.length-1)
		alist(href)
	}
	return false;
}



function ending(num)
{
	if(num%10==1 && num%100!=11) return '';
	if(num%10>=2 && num%10<=4 && (num%100<10 || num%100>20)) return 'а'; 
	return 'ов';
}

function ending2(num,e1,e2,e3)
{
	if(num%10==1 && num%100!=11) return e1;
	if(num%10>=2 && num%10<=4 && (num%100<10 || num%100>20)) return e2; 
	return e3;
}


function showform()
{
	document.getElementById("formdiv").style.display='block';
	document.getElementById("listdiv").style.display='none';
}



function showlist()
{
	if(document.getElementById("listdiv").innerHTML.length<20) {
		// нету у нас списка. обновляем форму чтобы стала пустой после нажатия "Отменить"
		return aform(preparedHref)		
	}
	document.getElementById("listdiv").style.display='block';
	document.getElementById("formdiv").style.display='none';
	document.getElementById("formdiv").innerHTML = formForAdd 
	tds = document.getElementsByTagName('button');
    for (var i = 0; i < tds.length; i++) 	{
			tds[i].onmouseover=function() { this.style.backgroundPosition='0px -26px' };
			tds[i].onmouseout=function() { this.style.backgroundPosition='0px 0px' };
	}		
}





function Init()
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Ваш браузер не поддерживает технологию, на которой работает система управления.")
		return
	} 
}


function GetXmlHttpObject(handler)
{ 
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
}


function reloadTree()
{
	$('stloader').setHTML('идёт загрузка структуры');
	st_load('');
}



function saveTree()
{
	querystring='';
	$$(".siteTree ul li").each(function(ul){
	  $ES("li", ul).each(function(li){
	  	if(li.getProperty('seen')!='yes')
		{
		  	i=0;
			li2=li;
		  	while(li2.getParent().getTag()=='ul' || li2.getParent().getTag()=='li'){
				li2 = li2.getParent();
				i++;
				}
			i=(i-1)/2 - 1;
		    querystring+=i+':'+li.id+'\n';
			li.setProperty('seen','yes');
		}
	  });
	});
	$('stloader').setHTML('идёт сохранение структуры');
	st_load(querystring);
}


function st_load(querystring){
	xmlHttp=GetXmlHttpObject()

	document.getElementById("stloader").style.display='block';
	
	var url="?ajaxpart=form&savetree="+escape(querystring)
	url+="&rand="+Math.floor(Math.random()*100000);
	xmlHttp.onreadystatechange=stLoaded 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	
	}
	
function stLoaded() { 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 		
		document.getElementById("formdiv").innerHTML = xmlHttp.responseText
		
		createNested();
	
		tds = document.getElementsByTagName('button');
	    for (var i = 0; i < tds.length; i++) 	{
				tds[i].onmouseover=function() { this.style.backgroundPosition='0px -26px' };
				tds[i].onmouseout=function() { this.style.backgroundPosition='0px 0px' };
		}		
		}
	} 
	
	
function newpage(pageid)
{
	href='?action=newpage&parent='+pageid;
	aform(href);
}
function editpage(pageid)
{
	href='?action=editpage&id='+pageid;
	aform(href);
}
function delpage(pageid,name)
{
	if(!confirm('Вы уверены, что хотите удалить страницу "'+name+'"?')) return;
	
	$('context').injectInside(document.body);
			
	$$('li.sortables ').each( function(li){
		if(li.id==pageid) li.remove();
	}
	);
	SetClassForLast();
	$('buttons').setStyle('visibility','visible');
}

	
function createNested(){
	$$(".treeview div").addEvent('mouseover', function(event){ if(!isDragged)this.addClass('hover') });
	$$(".treeview div").addEvent('mouseout', function(event){ this.removeClass('hover') });
	$$("ul.treeview").each(function(ul){
		new Nested(ul.id, {
			onStart: function(el) {	el.addClass('drag');},
			onComplete: function(el) { el.removeClass('drag');SetClassForLast(); }
		});
	});
	SetClassForLast();
	}

function SetClassForLast()
{
	$$(".treeview li").each(function(li,i){
		if(!li.getNext()) li.addClass('last');
		else li.removeClass('last');
	});
}





function astruct(href)
{
	xmlHttp=GetXmlHttpObject()

	document.getElementById("formfields").style.display = 'none'
	document.getElementById("formloader").style.display = ''
	document.getElementById("formdiv").style.display = 'block'
	document.getElementById("listdiv").style.display = 'none'
	
	if(href.indexOf('?')<0) href+='?'
	var url=href+"&ajaxpart=form"
	url+="&rand="+Math.floor(Math.random()*100000);
	xmlHttp.onreadystatechange=stLoaded 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
	
	
	return false
}




function context(event,id,that, title)
{
	active_id = id
	active_title = title
	if(window.ie)	$('context').setStyle('left',event.x-5).setStyle('top',event.y-5);
	else            $('context').setStyle('left',event.pageX-2).setStyle('top',event.pageY-2);
	$('context').injectInside(that);
	$('context').setStyle('display','block');
}


function turnfilter(){
	filters=''
	var re = /&?filter_[0-9a-zA-Z]+=\d*/g;
	sortbase = sortbase.replace(re,'')
	$$("select.filter_field").each(function(sel){
		if(filters[filters.length-1]!='&') filters+='&'
		filters+=sel.id+'='+sel.value;
	});
	newlink = sortbase+filters;
	return alist(newlink)
}

function turnsearchfilter(){
	filters='';
	var re = /&?filter_[0-9a-zA-Z]+=\d*/g;
	sortbase = sortbase.replace(re,'');
	
	filters+='filter_search='+$("filter_search").value+'&filter_status='+$("filter_status").value;
	newlink = sortbase+filters;
	return alist(newlink)
}


function makeResizeable()
{
	window.resizeObj = null;
	$$(".grippie").each(function(gr){
		if(window.ie) gr.setStyle('margin-right','2px');
		gr.addEvent('mousedown', window.startResize);
		});
}

window.startResize = function (event)
{
	document.addEvent('mousemove', window.moveResize);
	document.addEvent('mouseup', window.stopResize);
	//$$("iframe").each(function(ifr)	{	}	);
	if(window.ie)
		window.resizeObj = document.getElementById('area_'+event.srcElement.id);
	else
		window.resizeObj = document.getElementById('area_'+event.target.id);
}

window.moveResize = function (event)
{
	if(window.ie) var ey = event.y;
	else          var ey = event.pageY;
	var areacord = $(window.resizeObj).getCoordinates();
	var newheight = window.resizeObj.getStyle('height').toInt() + (ey - areacord['bottom']);
	if(newheight>30 && newheight<600 )	window.resizeObj.setStyle('height', newheight );
}

window.stopResize = function ()
{
	document.removeEvent('mousemove', window.moveResize);
	document.removeEvent('mouseup', window.stopResize);
}

function picChange(obj)
{
	if(obj.value)
	{
		document.getElementById('pic'+obj.name).style.display='block';
		document.getElementById('pic'+obj.name).src=obj.value;
	}
	else document.getElementById('pic'+obj.name).style.display='none';
}

function picCheck(name)
{
	if(!document.getElementById(name+'_check').checked)
	{
		document.getElementById(name+'_div').style.display='block';
	}
	else document.getElementById(name+'_div').style.display='none';
}

var image_for_window = null;
var tries_load_image=0;
var image_loading=0;
var image_timer_id=0;

function show_image_window(filename,event)
{
	if(window.ie) var ey = event.y;
	else          var ey = event.pageY;
	if(window.ie) var ex = event.x;
	else          var ex = event.pageX;
	$('image_window').setStyle('left',ex+5).setStyle('top',ey+5);
	
	if(image_for_window==null && image_loading==0)
	{
		image_for_window = new Image();
    	image_for_window.src = filename;//+'?rand='+Math.random();
		tries_load_image=0;
		image_loading=1;
		clearTimeout(image_timer_id);
		image_timer_id = setTimeout("set_image_in_window()",100);
	}
}

function set_image_in_window()
{
  if(!image_for_window || tries_load_image>100) {image_loading=0;image_timer_id=0;return;}
  if(!image_for_window.complete) {
    if(tries_load_image==5)
	{
		img_elem = document.getElementById('image_window_img');
		img_elem.src='/skins/admin/default/images/loader.gif';
		img_elem.width=32;
		img_elem.height=32;
		 $('image_window').setStyle('display','block');
	}
 	image_timer_id = setTimeout("set_image_in_window()",100);
	tries_load_image++;
	return;
 }
 img_elem = document.getElementById('image_window_img');
 img_elem.src='/skins/admin/default/images/dot.gif';
 img_elem.src=image_for_window.src;
 mn_x = image_for_window.width / 300;
 mn_y = image_for_window.height / 200;
 img_elem.height=image_for_window.height;
 img_elem.width=image_for_window.width;
 if(mn_x>1 || mn_y>1)
 {
	if(mn_y>mn_x) {
		img_elem.height=300;
		img_elem.width = image_for_window.width*(300/image_for_window.height);
		}
	else {
		img_elem.width=200;
		img_elem.height = image_for_window.height*(200/image_for_window.width);
		}			
 }
 $('image_window').setStyle('display','block');
 image_loading=0;
 image_timer_id=0;
}

function reset_image_window()
{
    image_for_window=null;
	$('image_window').setStyle('display','none');
}



var library_initialized=false;

function show_library(library_object, library_div, library_field )
{
	if($(library_div).getStyle('display')=='block') {
		$(library_div).setStyle('display','none');
		$('library_button').value='Выбрать из существующих картинок';
		return;
	}
	if(!library_initialized)
	{
		i=1;
		for (var num in library_object)
		{
			ni = new Element('img', {
		        'src': library_object[num].imagepath+'?rand='+Math.random()
		      });
			if(library_object[num].width>120) ni.setProperty('width','120');
			nd = new Element('div',{
				'events': {
		           'mouseover': function(){
		               this.style.background='#E4F5B2';
		            },
		           'mouseout': function(){
		               this.style.background='';
		            },
					'click': function(){
						select_library_image(this.childNodes[0]);
					}
		        }			
				});
			
			if(i%2) {
				nbr = new Element('br');
				nbr.setStyle('clear','both');
				nbr.injectInside($(library_div));
				}
			ni.injectInside(nd);
			nd.injectInside($(library_div));
			i++;
		}
		library_initialized=true;
	}
	$(library_div).setStyle('display','block');
	$('library_button').setProperty('value','Скрыть список картинок');
}


function select_library_image(img)
{
	$('library_button').setStyle('display','none');
	$('library_div').setStyle('display','none');
	$('library_chosen').setStyle('display','block');
	$$('#library_chosen img').setProperty('src', img.src);
	$$('#library_chosen img').setProperty('width', img.width);
	$('library_button').setProperty('value','Выбрать из существующих картинок');
	$('library_hidden').setProperty('value',img.src);
}

function cancel_library_image()
{
	$('library_button').setStyle('display','block');
	$('library_chosen').setStyle('display','none');
	$('library_hidden').setProperty('value','');
}







function populateTwin(twin_name,value)
{
	var select2 = document.getElementById('input_'+twin_name+'_second');
	var str='';
	for(var i=0; i<twins[twin_name][value].length; i++)
	{
		str += '<option value="'+twins[twin_name][value][i][0]+'">'+twins[twin_name][value][i][1];
	}
	select2.innerHTML=str;
}